package com.atguigu.gmall.realtime.util;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.annotation.NoSink;
import com.atguigu.gmall.realtime.bean.ProductStats;
import com.atguigu.gmall.realtime.bean.TableProcess;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.sink.PhoenixSink;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author lzc
 * @Date 2022/4/14 16:04
 */
public class FlinkSinkUtil {
    public static SinkFunction<String> getKafkaSink(String topic) {
        
        Properties props = new Properties();
        props.put("bootstrap.servers", Constant.KAFKA_BROKERS);
        props.put("transaction.timeout.ms", 15 * 60 * 1000);
        
        
        return new FlinkKafkaProducer<String>(
            "default",
            new KafkaSerializationSchema<String>() {
                
                @Override
                public ProducerRecord<byte[], byte[]> serialize(String element,
                                                                @Nullable Long timestamp) {
                    return new ProducerRecord<>(topic, element.getBytes(StandardCharsets.UTF_8));
                }
            },
            props,
            FlinkKafkaProducer.Semantic.EXACTLY_ONCE
        );
    }
    
    public static SinkFunction<Tuple2<JSONObject, TableProcess>> getKafkaSink() {
        Properties props = new Properties();
        props.put("bootstrap.servers", Constant.KAFKA_BROKERS);
        props.put("transaction.timeout.ms", 15 * 60 * 1000);
        
        return new FlinkKafkaProducer<Tuple2<JSONObject, TableProcess>>(
            "default",
            new KafkaSerializationSchema<Tuple2<JSONObject, TableProcess>>() {
                @Override
                public ProducerRecord<byte[], byte[]> serialize(Tuple2<JSONObject, TableProcess> element,
                                                                @Nullable Long timestamp) {
                    JSONObject data = element.f0;
                    String topic = element.f1.getSink_table();
                    
                    return new ProducerRecord<>(topic, data.toJSONString().getBytes(StandardCharsets.UTF_8));
                }
            },
            props,
            FlinkKafkaProducer.Semantic.EXACTLY_ONCE
        );
        
    }
    
    public static SinkFunction<Tuple2<JSONObject, TableProcess>> getPhoenixSink() {
        
        return new PhoenixSink();
    }
    
    public static <T> SinkFunction<T> getClickHouseSink(String db, String table, Class<T> tClass) {
        // 在jdbc sink的基础上, 封装一个clickhouse sink
        String driver = Constant.CLICKHOUSE_DRIVER;
        String url = Constant.CLICKHOUSE_URL_PRE + db;
        
        StringBuilder sql = new StringBuilder();
        // 拼接sql  将来表中的字段的名字要和t这个类中的属性名保持一致
        // insert into t(a,b,c)values(?,?,?)
        
        Field[] fields = tClass.getDeclaredFields();
        String columns = Stream.of(fields)
            .filter(f -> f.getAnnotation(NoSink.class) == null)  // 没有注解的流下来
            .map(Field::getName)
            .collect(Collectors.joining(","));
        
        sql
            .append("insert into ")
            .append(table)
            .append("(")
            .append(columns)
            .append(")values(")
            .append(columns.replaceAll("[^,]+", "?"))
            .append(")");
        
        
        System.out.println("clickhosue插入语句:" + sql.toString());
        return getJdbcSink(driver, url, null, null, sql.toString());
    }
    
    public static void main(String[] args) {
        getClickHouseSink("a", "ab", ProductStats.class);
    }
    
    private static <T> SinkFunction<T> getJdbcSink(String driver,
                                                   String url,
                                                   String userName,
                                                   String password,
                                                   String sql) {
        return JdbcSink.sink(sql,
                             new JdbcStatementBuilder<T>() {
                                 @Override
                                 public void accept(PreparedStatement ps,
                                                    T t) throws SQLException {
                                     // 给占位符赋值! TODO
                                     // Class.forName  类名.class 对象.getClass
                
                                     Class<?> tClass = t.getClass();
                                     Field[] fields = tClass.getDeclaredFields();
                                     try {
                                         for (int i = 0, position = 1; i < fields.length; i++) {
                                             Field field = fields[i];
                                             if (field.getAnnotation(NoSink.class) == null) {
                                                 field.setAccessible(true); // 允许访问私有属性
                                                 Object v = field.get(t);  // 获取对象中属性的值
                                                 ps.setObject(position++, v); // 计算器要单独
                                             }
                                         }
                                     } catch (IllegalAccessException e) {
                                         e.printStackTrace();
                                     }
                
                                 }
                             },
                             new JdbcExecutionOptions.Builder()
                                 .build(),
                             new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                                 .withDriverName(driver)
                                 .withUrl(url)
                                 .withUsername(userName)
                                 .withPassword(password)
                                 .build()
        );
    }
    
    
}
